import {getEmployeeInfo, getEmployeeInfoByRoleanddepartment} from "@/api/employeeApi";
import {submitAnnualLeave } from '@/api/annualleaveApi';
export default {
    name: 'AnnualLeaveApply',
    data() {
        // 自定义天数验证规则
        const validateDays = (rule, value, callback) => {
            if (value > this.remainingDays) {
                callback(new Error(`超出剩余天数（剩余${this.remainingDays}天）`));
            } else {
                callback();
            }
        };

        return {
            form: {
                startDate: null,    // 日期选择器绑定值
                days: 1,            // 请假天数
                approverId: null,   // 审批人ID
                remarks: ''         // 备注
            },
            remainingDays: {}, // 从后端获取的剩余天数
            search:{},
            approvers: [],    // 原始审批人列表
            submitting: false,
            rules: {
                startDate: [
                    { required: true, message: '请选择开始日期', trigger: 'blur' }
                ],
                days: [
                    { required: true, message: '请输入休假天数', trigger: 'blur' },
                    { type: 'number', min: 1, message: '天数必须大于0', trigger: 'blur' },
                    { validator: validateDays, trigger: 'blur' }
                ],
                approverId: [
                    { required: true, message: '请选择审批人', trigger: 'change' }
                ]
            },
            dateOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                }
            }
        }
    },
    computed: {
    },
    async created() {
        await this.fetchRemainingDays();
        await this.fetchApprovers();
    },

    methods: {

        // 获取剩余天数
        async fetchRemainingDays() {
            try {
                // 1. 获取员工ID（从登录态）
                this.search.account = window.sessionStorage.getItem('empId');
                // 2. 调用API获取员工信息
                const empResult = await getEmployeeInfo(this.search.account);
                if (empResult.code === 200) {
                    this.remainingDays = empResult.data.remainingAnnualLeave;
                }
            } catch (error) {
                this.$message.error('获取剩余天数失败');
            }
        },

        // 获取审批人列表
        async fetchApprovers() {
            try {
                // 获取当前用户部门ID（根据实际存储位置调整）
                // const currentDept = parseInt(sessionStorage.getItem('departmentId')) || 0;

                // 调用API获取审批人数据
                const response = await getEmployeeInfoByRoleanddepartment(3,1);
                // 合并结果
                this.approvers = response.data;
                // alert(JSON.stringify(response.data, null, 2));
            } catch (error) {
                this.$message.error('获取审批人失败: ' + (error.message || '未知错误'));
                console.error('审批人加载失败:', error);
            }
        },

        // 提交处理
        async submitForm() {
            try {
                // 参数组装（与后端严格一致）
                const params = {
                    employeeId: sessionStorage.getItem('empId'),
                    operator: this.form.approverId,//有问题
                    startDate: this.formatDate(this.form.startDate),
                    daysLeave: this.form.days,
                    remark: this.form.remarks || '无'
                };

                // 发送请求
                const result = await submitAnnualLeave(params);
                if (result.code === 200) {
                    this.$message.success(`申请成功！`);
                    // this.$router.push('/success');
                } else {
                    this.$message.error(`提交失败: ${result.message}`);
                }
            } catch (error) {
                console.error("请求失败:", error);
            }
        },
        formatDate(date) {
            if (!date) return '';

            const d = new Date(date);
            // 处理Invalid Date
            if (isNaN(d.getTime())) {
                console.error('Invalid date:', date);
                return '';
            }

            const year = d.getFullYear();
            const month = (d.getMonth() + 1).toString().padStart(2, '0');
            const day = d.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        },


        // 重置表单
        resetForm() {
            this.$refs.annualLeaveForm.resetFields();
            this.form.days = 1;
        }
    }
}
